package usables;

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.xml.sax.InputSource;
import handler.VideoHandler;
import java.io.*;
import java.util.*;
import org.xmldb.api.base.*;
import org.xmldb.api.base.Collection;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;
import org.exist.xmldb.XQueryService;
import structures.Video;
import structures.Query;

/**
 * Using Video Hanler Test Class
 * @author Jose Antonio Prieto
 */
public class UsingVideoHandler {

    @SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {

        // Here we will store the Video objects
        Map<String, Video> videos = new HashMap<String, Video>();

        // Initialize the driver of the database
        String driver = "org.exist.xmldb.DatabaseImpl";
        String URI = "xmldb:exist://localhost:8080/exist/xmlrpc/db/DatabaseApplication";
        Class cl = Class.forName(driver);
        Database database = (Database) cl.newInstance();
        DatabaseManager.registerDatabase(database);

        // Obtain the collection and launch the query, obtaining a set o results. 	    
        Collection col = DatabaseManager.getCollection(URI);
        XQueryService service = (XQueryService) col.getService("XQueryService", "1.0");
        Query qry = new Query();
        qry.loadQuerys();
        ResourceSet result = service.query(qry.getVideoURLFromId("v000002"));

        // Iterate through the set of results, which are XML elements of type photo 
        // (note that the resources are taken as XMLResources!). 
        // Each XMLResource is processed by the SAX handler (we provide the handler 
        // with a new Photo object so it can store the parsed information).
        // The obtained objects are stored in the HashMap images. 
        ResourceIterator i = result.getIterator();
        while (i.hasMoreResources()) {
            XMLResource r = (XMLResource) i.nextResource();
            Video ph = new Video();
            VideoHandler handler = new VideoHandler(ph);
            r.getContentAsSAX(handler);
            videos.put(ph.getId(), ph);
        }

        // Print the photo objects we have obtained
        List<String> phs = new ArrayList<String>(videos.keySet());
        Collections.sort(phs);
        for (Iterator iterator = phs.iterator(); iterator.hasNext();) {
            String id = (String) iterator.next();
            System.out.println(videos.get(id));
        }
    }
}
